package com.yang.flower.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.flower.common.Result;
import com.yang.flower.config.AuthAccess;
import com.yang.flower.entity.Flower;
import com.yang.flower.entity.User;
import com.yang.flower.mapper.FileMapper;
import com.yang.flower.mapper.FlowerMapper;
import com.yang.flower.service.FlowerService;
import com.yang.flower.utils.TokenUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description: 鲜花管理
 * @Author: Yang
 * @DateTime: 2022/12/5 20:35
 **/
@RestController
@CrossOrigin
@RequestMapping("/flower")
public class FlowerController {

    @Autowired
    private FlowerService flowerService;

    @Resource
    private FlowerMapper flowerMapper;

    //分页查询及检索鲜花信息
    @GetMapping("/page")
    public Page<Flower> page(@RequestParam Integer pageNum,
                             @RequestParam Integer pageSize,
                             @RequestParam String name,
                             @RequestParam String code){
        Page<Flower> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Flower> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Flower::getName,name).like(Flower::getCode,code);
        queryWrapper.orderByDesc(Flower::getId);
        Page<Flower> pageInfo = flowerService.page(page, queryWrapper);
        return pageInfo;
    }

    //添加鲜花
    @PostMapping("/save")
    public Result save(@RequestBody Flower flower){
        flower.setCreateTime(LocalDateTime.now());
        flower.setCreateUser(TokenUtils.getCurrentUser().getUsername());
        return Result.success(flowerService.save(flower));
    }

    //修改鲜花信息
    @PutMapping("/edit")
    public Result edit(@RequestBody Flower flower){
        return Result.success(flowerService.updateById(flower));
    }

    //修改鲜花销售状态
    @PutMapping("/changeStatus/{id}")
    public Result changeStatus(@PathVariable("id") Integer id){
        LambdaQueryWrapper<Flower> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Flower::getId,id);
        Flower flower = flowerService.getOne(queryWrapper);
        String newStatus = flower.getStatus().equals("起售") ? "停售" : "起售";
//        flower.setStatus(newStatus);
        flowerService.saveOrUpdate(flower);
        return Result.success(newStatus);
    }

    //根据id获取鲜花信息
    @AuthAccess
    @GetMapping("/{id}")
    public Result findOne(@PathVariable("id") Integer id){
        return Result.success(flowerService.getById(id));
    }

    //根据id删除鲜花
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id){
        return Result.success(flowerService.removeById(id));
    }

    //根据勾选,批量删除鲜花
    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(flowerService.removeByIds(ids));
    }

    //导出
    @AuthAccess
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Flower> list = flowerService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("name", "鲜花名称");
        writer.addHeaderAlias("price", "鲜花价格");
        writer.addHeaderAlias("code", "商品码");
        writer.addHeaderAlias("status", "销售状态");
        writer.addHeaderAlias("description", "描述");
        writer.addHeaderAlias("categoryId", "鲜花分类Id");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("createUser", "创建人");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("鲜花信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    @AuthAccess
    @GetMapping("/frontPage")
    public Result frontAll(){
        return Result.success(flowerMapper.selectList(null));
    }

    @GetMapping("/queryByPurpose/{purpose}")
    public Result queryByPurpose(@PathVariable("purpose") String purpose){
        List<Flower> flowerList = flowerMapper.queryByPurpose(purpose);
        return Result.success(flowerList);
    }

    @GetMapping("/queryByConstitute/{constitute}")
    public Result queryByConstitute(@PathVariable("constitute") String constitute){
        List<Flower> flowerList = flowerMapper.queryByConstitute(constitute);
        return Result.success(flowerList);
    }

    @GetMapping("/queryBySales")
    public Result queryBySales(){
        LambdaQueryWrapper<Flower> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Flower::getSales);
        List<Flower> flowerList = flowerService.list(queryWrapper);
        return Result.success(flowerList);
    }

    @GetMapping("/searchByCondition")
    public Result searchByCondition(@RequestParam String checkList,
                                    @RequestParam String checkList2,
                                    @RequestParam String message){
        System.out.println("checkList2：" + checkList2);
        System.out.println("查看checkList1:" + checkList);
        System.out.println("message:" + message);
        List<Flower> totalList = new ArrayList<>();

        //用户输入了信息,未勾选条件
        if(message != null && checkList.equals("") && checkList2.equals("")){
            LambdaQueryWrapper<Flower> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(Flower::getTargets,message);
            List<Flower> flowers = flowerService.list(lambdaQueryWrapper);
            totalList.addAll(flowers);
        }else{
            //用户价格及适用均未勾选
            if(checkList.equals("") && checkList2.equals("")){
                LambdaQueryWrapper<Flower> flowerLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                List<Flower> list = flowerService.list(flowerLambdaQueryWrapper2);
                totalList.addAll(list);
            }else{
                //若用户未勾选价格,而勾选了适用
                if(checkList.equals("")){
                    List<String> list = Arrays.asList(checkList2.split(","));
                    for (String s : list) {
                        LambdaQueryWrapper<Flower> flowerLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        flowerLambdaQueryWrapper.like(Flower::getTargets,s);
                        List<Flower> flowers = flowerService.list(flowerLambdaQueryWrapper);
                        totalList.addAll(flowers);
                    }
                }else if (checkList2.equals("")){
                    List<String> priceList = Arrays.asList(checkList.split(","));
                    List<String> targetList = Arrays.asList(checkList2.split(","));
                    for (String price : priceList) {
                        if(price.contains("-")){
                            String[] split = price.split("-");
                            for (String s : targetList) {
                                LambdaQueryWrapper<Flower> queryWrapper3 = new LambdaQueryWrapper<>();
                                queryWrapper3.le(Flower::getPrice,split[1]).ge(Flower::getPrice,split[0]);
                                queryWrapper3.like(Flower::getTargets,s);
                                List<Flower> flowerList3 = flowerService.list(queryWrapper3);
                                totalList.addAll(flowerList3);
                            }
                        }else{
                            if(price.equals("100")){
                                for (String s : targetList) {
                                    LambdaQueryWrapper<Flower> queryWrapper1 = new LambdaQueryWrapper<>();
                                    queryWrapper1.like(Flower::getTargets,s);
                                    queryWrapper1.le(Flower::getPrice,price);
                                    List<Flower> flowerList1 = flowerService.list(queryWrapper1);
                                    totalList.addAll(flowerList1);
                                }
                            }else{
                                LambdaQueryWrapper<Flower> queryWrapper2 = new LambdaQueryWrapper<>();
                                queryWrapper2.ge(Flower::getPrice,price);
                                List<Flower> flowerList2 = flowerService.list(queryWrapper2);
                                totalList.addAll(flowerList2);
                            }
                        }
//                    totalList.addAll(flowers);
                    }
                }else{
                    //用户同时勾选了价格及适用
                    LambdaQueryWrapper<Flower> queryWrapper = new LambdaQueryWrapper<>();
                    List<String> priceList = Arrays.asList(checkList.split(","));
                    List<String> targetList = Arrays.asList(checkList2.split(","));

                    for (String price : priceList) {
                        if(price.contains("-")){
                            String[] split = price.split("-");
                            for (String s : targetList) {
                                LambdaQueryWrapper<Flower> queryWrapper3 = new LambdaQueryWrapper<>();
                                queryWrapper3.le(Flower::getPrice,split[1]).ge(Flower::getPrice,split[0]);
                                queryWrapper3.like(Flower::getTargets,s);
                                List<Flower> flowerList3 = flowerService.list(queryWrapper3);
                                totalList.addAll(flowerList3);
                            }
                        }else{
                            if(price.equals("100")){
                                for (String s : targetList) {
                                    LambdaQueryWrapper<Flower> queryWrapper1 = new LambdaQueryWrapper<>();
                                    queryWrapper1.like(Flower::getTargets,s);
                                    queryWrapper1.le(Flower::getPrice,price);
                                    List<Flower> flowerList1 = flowerService.list(queryWrapper1);
                                    totalList.addAll(flowerList1);
                                }
                            }else{
                                LambdaQueryWrapper<Flower> queryWrapper2 = new LambdaQueryWrapper<>();
                                queryWrapper2.ge(Flower::getPrice,price);
                                List<Flower> flowerList2 = flowerService.list(queryWrapper2);
                                totalList.addAll(flowerList2);
                            }
                        }
                    }
                    System.out.println("priceList"+priceList);
                }
            }
        }

        Iterator<Flower> iterator = totalList.iterator();
        while(iterator.hasNext()){
            Flower next = iterator.next();
            if(totalList.indexOf(next) != totalList.lastIndexOf(next)){
                iterator.remove();
            }
        }
        return Result.success(totalList);
    }
 }

